﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BLToolkit.Data;
using BLToolkit.Data.Linq;
using Devsoft.DB.Models.EditableObject;

namespace Devsoft.DB.Models.Linq
{
    public static class Extensions
    {
        
        public static System.Linq.IQueryable<TSource> Filter<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,int,bool>> predicate)
        {
            return source.Where(predicate);
        }

        public static System.Linq.IQueryable<TSource> Filter<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, bool>> predicate)
        {
            return source.Where(predicate);
        }

        public static void Delete<T>(this IEnumerable<T> source, int batchSize = int.MaxValue) where T : IModel
        {
            DbManager manager = DBRouter.Default.GetDB<T>();
            manager.Delete(batchSize,source);
        }

        public static void Insert<T>(this IEnumerable<T> source,int batchSize = int.MaxValue) where T : IModel
        {
            DbManager manager = DBRouter.Default.GetDB<T>();
            manager.InsertBatch(batchSize,source);
        }



        public static void Remove<T>(this System.Linq.IQueryable<T> source) where T : IModel
        {
            source.Delete();
        }
        
        public static TSource Latest<TSource, TKey>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector)
        {
            return source.OrderByDescending(keySelector).First();
        }
    }
}
